package cn.btks.commonserver.valid.impl;


import cn.btks.commonserver.valid.LengthValid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.UnsupportedEncodingException;

/**
 * zhangjing 2019/12/13.
 */
public class LengthValidImpl implements ConstraintValidator<LengthValid, String> {

    //记录字节长度
    private int byteCount;

    //编码方式（默认GBK，还有"UTF-8"、"ISO8859-1"、"GB2312"等）
    private String decoding;

    @Override
    public void initialize(LengthValid constraintAnnotation) {
        this.byteCount = constraintAnnotation.byteCount();
        this.decoding = constraintAnnotation.decoding();
    }

    @Override
    public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) {
        if (str == null) {
            return true;
        }
        byte[] buff = new byte[0];
        try {
            buff = str.getBytes(decoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int i = buff.length;
        return i <= byteCount;
    }
}
